package cn.xutongxue.interview.job.cycle;

import cn.hutool.core.collection.CollUtil;
import cn.xutongxue.interview.entity.Question;
import cn.xutongxue.interview.es.dao.QuestionEsDao;
import cn.xutongxue.interview.es.entity.QuestionEsEntity;
import cn.xutongxue.interview.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 增量同步题目数据到ES
 * @author Administrator
 */
@Component
@Slf4j
public class IncSyncQuestionToEs {

    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedDelay = 60 * 1000)
    public void run() {
        long MINUTE_RANGE = 5 * 60 * 1000L;
        Date fiveMinuteAgo = new Date(new Date().getTime() - MINUTE_RANGE);
        List<Question> questionList = questionService.listQuestionWitheDelete(fiveMinuteAgo);
        if (CollUtil.isEmpty(questionList)) {
            log.info("no inc question");
            return;
        }
        // 数据类型转换
        List<QuestionEsEntity> questionEsEntityList = questionList.stream().map(QuestionEsEntity::objToEsEntity).collect(Collectors.toList());
        // 分页导入ES
        final int pageSize = 500;
        int total = questionEsEntityList.size();
        log.info("FullSyncQuestionToEs start, total num:{}", total);
        for (int i = 0; i < pageSize; i += pageSize) {
            // 防止下标超过数据总数
            int end = Math.min(i + pageSize, total);
            log.info("sync from {}, to {}", i, end);
            questionEsDao.saveAll(questionEsEntityList.subList(i, end));
        }
        log.info("FullSyncQuestionToEs end, total num:{}", total);
    }
}
